import { LOGIN_TOKEN_KEY } from "@/global/constants"
import { localCache } from "@/utils/cache"
import {
  createRouter,
  createWebHistory
} from "vue-router"

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect: "/main",
    },
    {
      name: "login",
      path: "/login",
      component: () => import("@/views/login/login.vue"),
    },
    {
      name: "main",
      path: "/main",
      component: () => import("@/views/main/main.vue"),
      children: [
        {
          path: "",
          redirect: "/main/dispatch"
        }, {
          name: "dispatch",
          path: "/main/dispatch",
          component: () => import("@/views/main/dispatch/dispatch.vue")
        }, {
          name: "wokerList",
          path: "/main/wokerList",
          component: () => import("@/views/main/woker/woker-list.vue")
        }, {
          name: "customerServiceList",
          path: "/main/customerServiceList",
          component: () => import("@/views/main/customer-service/customer-service-list.vue")
        }
      ]
    },
    {
      path: "/:pathMatch(.*)*",
      component: () => import("@/views/not-found/NotFound.vue"),
    }
  ],
})

// 导航守卫
router.beforeEach((to, from) => {
  const token = localCache.getCache(LOGIN_TOKEN_KEY)
  if (to.path.startsWith('/main') && !token) {
    return '/login'
  }
})

export default router